#include "soc_uart.h"
#include "soc_misc.h"
#include "soc_cfg.h"

void SOC_UartInit(SOC_UartNo_t no, uint32_t baudrate)
{
	uint8_t bd;

	if(no != S_UART0)
		return;

	bd = 0xff - (SOC_GetCpuFrequency() / 12.0 / baudrate / 2 / 32);

	TMOD |= 0x20;        //使用定时工作方式2
	TL1 = bd;       //设定定时初值
	TH1 = bd;       //设定定时器重装值
	PCON = 0x00;        //波特率不倍速
	SCON = 0x50;		//

	REN = 1;
	ES = 0;
	TR1 = 1;            //打开定时器中断
}

void SOC_UartSendByte(SOC_UartNo_t no, uint8_t b)
{
	if(no != S_UART0)
		return;

	SBUF = b;
	while( !(SCON & (1<<1)));
	SCON &=~(1<<1);
}

void SOC_UartSend(SOC_UartNo_t no, uint8_t *buffer, int len)
{
	int i;

	if(no != S_UART0)
		return;

	for(i = 0; i < len; i++)
	{
		SOC_UartSendByte(no, buffer[i]);
	}
}

void SOC_UartSendString(SOC_UartNo_t no, uint8_t *str)
{
	if(no != S_UART0)
		return;

	while(*str != '\0')
	{
		SOC_UartSendByte(no, *str++);
	}
}

int SOC_ReadByteBlock(SOC_UartNo_t no)
{
	if(no != S_UART0)
		return -1;

	while(!(SCON & (1<<0)));
	SCON &=~(1<<0);
	return  SBUF;	
}

int SOC_ReadByte(SOC_UartNo_t no)
{
	if(no != S_UART0)
		return -1;

	if(!(SCON & (1<<0)))
		return -1;

	SCON &=~(1<<0);
	return  SBUF;	
}

void SOC_UartSetEnableRx(SOC_UartNo_t no, bool en)
{
	if(no != S_UART0)
		return;

	REN = en? 1:0;
}

void SOC_UartSetEnableRx_IT(SOC_UartNo_t no, bool en)
{
	if(no != S_UART0)
		return;

	ES = en? 1:0;
}

char putchar (char ch)
{
	SOC_UartSendByte(SOC_LOG_UART_NO, (uint8_t)ch);
	return 0;
}

char getchar (void)
{
	return SOC_ReadByte(SOC_LOG_UART_NO);
}

int  puts( const char  * s)
{
	while(*s)
	{
		putchar(*s);
		s++;		
	}
	return 0;
}
